import Qs from 'qs'
import { Message, Loading } from 'element-ui';
import router from '@/router/index'
import Vue from 'vue';
// 配置API接口地址
var root = process.env.API_URL
// 引用axios
var axios = require('axios')

/** 全局加载loading ==========================================开始 */
let loading        //定义loading变量

function startLoading() {    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {    //使用Element loading-close 方法
    loading.close()
}
//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}

//http request 拦截器
axios.interceptors.request.use(
    config => {
        showFullScreenLoading()
        return config;
    },
    error => {
        return Promise.reject(err);
    }
);
 
//http response 拦截器
axios.interceptors.response.use(
    response => {
        // //当返回信息为未登录或者登录失效的时候重定向为登录页面
        // if(response.data.code == 'W_100004' || response.data.message == '用户未登录或登录超时，请登录！'){
        //     router.push({
        //         path:"/",
        //         querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
        //     })
        // }
        tryHideFullScreenLoading()
        return response;
    },
    error => {
        endLoading()
        let http_codes = {
            400: '错误请求',
            401: '未授权',
            402: '需要付款',
            403: '禁止访问',
            404: '接口文档地址不正确',
            405: '不允许使用该方法',
            406: '无法接受',
            407: '要求代理身份验证',
            408: '请求超时',
            409: '冲突',
            410: '已失效',
            411: '需要内容长度头',
            412: '预处理失败',
            413: '请求实体过长',
            414: '请求网址过长',
            415: '媒体类型不支持',
            416: '请求范围不合要求',
            417: '预期结果失败',
            500: '内部服务器错误',
            501: '未实现',
            502: '网关错误',
            503: '服务不可用',
            504: '网关超时',
            505: 'HTTP版本不受支持'
        };
        if (error.response && http_codes[error.response.status]) {
            window.alert(error.response.status + ': ' + http_codes[error.response.status]);
        } else {
            window.alert('网络访问出现异常，请检测网络！');
        }
        return Promise.reject(error)
    }
)
 
/** 全局加载loading ==========================================结束 */


// 自定义判断元素类型JS
function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull (o) {
  for (var key in o) {
    if (o[key] == null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}

/**
 * 跳转到退出的地址
 */
function goLoginPage(){
    var result = process.env.EXIT_URL;
    var platformId = Vue.prototype.$sessionStore.getPlatformId();
    if(!platformId) return result;
    let param = {};
    param.platformId = platformId;
    $.ajax({
        url: process.env.API_URL + "vueapi/user/getPlatformNameOfLogin",
        type: "POST",
        async: false,
        data: param,
        timeout: 5000,
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
            console.info(data);
            if(data.code == "0"){
                result=data.data.loginOutUrl;
            }
        }
      });
      top.location.href = result;
}

/*
 接口处理函数
*/
function apiFormAxios (method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  axios({
    // headers: {'Content-Type': 'multipart/form-data'},
    headers: { 'Content-Type': 'application/x-www-form-urlencode' },
    method: method,
    url: url,
    data: (method === 'POST' || method === 'PUT') ? params : null,
    params: (method === 'GET' || method === 'DELETE') ? params : null,
    baseURL: root,
    withCredentials: true
  }).then(function (res) {
    if (res.data.status === 600) {
        goLoginPage();
    } else {
      if (success) {
        success(res.data)
      }
    }
  }).catch(function (err) {
    let res = err.response
    if (err) {
      window.alert('api error, HTTP CODE: ' + res)
    }
  })
}

function apiAxios (method, url, params, success, failure) {
  var uuid = Vue.prototype.$util.UUID();    //加上随机数防止ie浏览器缓存
  if (params) {
    params = filterNull(params);
    params.t=uuid
  } else {
    params={t:uuid};
  }
  axios({
    method: method,
    url: url,
    data: (method === 'POST' || method === 'PUT') ? Qs.stringify(params, { indices: false }) : null,
    params: (method === 'GET' || method === 'DELETE') ? params : null,
    baseURL: root,
    withCredentials: true
  }).then(function (res) {
    if(res.data == null){
        window.alert('网络访问出现异常');
        return; 
    }
    if (res.data.code === '600') {
        let curPath = router.currentRoute.path;
        if(curPath.startsWith('/mobile')){
            router.push({ path: '/mobileLogin'});
        }else {
            goLoginPage();
        }
    } else {
        if (success) {
            success(res.data)
        }
    }
  }).catch(function (err) {
    let res = err.response
    if (err) {
      window.alert('网络访问出现异常,请检测网络！');
      console.info(err);
    }
  })
}

// 返回在vue模板中的调用接口
export default {
  get: function (url, params, success, failure) {
    return apiAxios('GET', url, params, success, failure)
  },
  post: function (url, params, success, failure) {
    return apiAxios('POST', url, params, success, failure)
  },
  put: function (url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure)
  },
  delete: function (url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure)
  },
  formpost: function (url, params, success, failure) {
    return apiFormAxios('POST', url, params, success, failure)
  }
}



// WEBPACK FOOTER //
// ./src/api/index.js

'cc33abe2-457e-47c0-8763-1194bf26ec8e'
method = "GET", url = "/vueapi/trainplan/trainplanClassifys", params = null, success = ƒ (e), failure = undefined
uuid = "3bdbf331-2387-4657-be83-aa78f28e6445"

method = "GET", url = "/vueapi/trainplan/list", params = {isFinish: 0, pageSize: 5, curPage: 1, trainplanType: ""}, success = ƒ (e), failure = undefined
uuid = "01a506d9-48ae-48cc-87f4-5be24bb4e228"

method = "GET", url = "/vueapi/common/footer", params = null, success = ƒ (n), failure = undefined
uuid = "4c1adfae-f094-4017-8602-054bd628b579"

method = "GET", url = "/vueapi/cart/getCartCount", params = null, success = ƒ (n), failure = undefined
uuid = "20272555-20f2-470c-82e3-4a8a2de84164"